﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ArgusLib.Fractals;

namespace Fraktalysator.Forms
{
	partial class ProgressForm : ArgusLib.Controls.ProgressBox
	{
		TimeSpan pauseTime;
		DateTime lastProgressSet;
		PerformanceCounter performanceCounter;

		public ProgressForm()
		{
			InitializeComponent();
			this.ShowProcessTasksPanel = true;
			this.pauseTime = new TimeSpan(0, 0, 0, 0, 250);
			this.lastProgressSet = DateTime.Now;
			if (PerformanceCounterCategory.CounterExists("Available MBytes", "Memory"))
			{
				this.performanceCounter = new PerformanceCounter("Memory", "Available MBytes");
			}
		}

		public void SetFractalProgress(CalculationProgressChangedEventArgs e)
		{
			if (DateTime.Now - this.lastProgressSet < this.pauseTime)
				return;

			if (ArgusLib.Environment.Runtime == ArgusLib.Runtime.Mono)
			{
				if (this.IsShown == false)
					return;
			}

			if (this.InvokeRequired == false)
				this.SetFractalProgressInvoke(e);
			else
				this.Invoke(new Action<CalculationProgressChangedEventArgs>(this.SetFractalProgressInvoke), e);
		}

		void SetFractalProgressInvoke(CalculationProgressChangedEventArgs e)
		{
			this.SetProgress(e.Progress);
			this.SetProgressProcessedTasks((int)e.Data[0], (int)e.Data[1]);
			this.lElapsedTime.Text = e.ElapsedTime.ToString(Localization.Formats.Time);
			float usedMemory = (float)System.Environment.WorkingSet / (1 << 20);
			this.lUsedMemory.Text = usedMemory.ToString("n0")+" MB";
			if (this.performanceCounter != null)
			{
				float freeMemory = this.performanceCounter.NextValue();
				this.lFreeMemory.Text = freeMemory.ToString("n0") + " MB";
			}
			this.lastProgressSet = DateTime.Now;
		}

		protected override void OnFormClosed(FormClosedEventArgs e)
		{
			if (ArgusLib.Environment.Runtime != ArgusLib.Runtime.Mono)
				this.SetFractalProgress(new CalculationProgressChangedEventArgs(0, new TimeSpan(0), 0, 0));
			base.OnFormClosed(e);
		}
	}
}
